package com.xingfly.interceptor;


import org.apache.log4j.Logger;
import org.springframework.core.NamedThreadLocal;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 实现统计应用性能 拦截器 的实现是单例的，因此不管用户请求多少次 都 只访问一个拦截器实例，即线程不安全
 * 解决方案：使用ThreadLocal,它是线程绑定的变量，提供线程局部变量 (一个线程一个ThreadLocal)
 * Created by SuperS on 2019/5/29.
 * 算法时间计算拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {
	public static final Logger logger1 =Logger.getLogger(LoginInterceptor.class);
	//public static final Logger logger2 =Logger.LoggerFactory.getLogger(LoginInterceptor.class);
    // 统计应用性能
    private NamedThreadLocal<Long> startTimeThreadLocal = new NamedThreadLocal<>("StopWatch-StartTime");
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
    	// 1,开始时间
        long startTime = System.currentTimeMillis();
        // 线程绑定变量(该数据只有当前请求的线程可见)
        startTimeThreadLocal.set(startTime);
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    	
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    	// 2.结束时间
        long endTime = System.currentTimeMillis();
        // 得到线程绑定的局部 变量(开始时间)
        long beginTime = startTimeThreadLocal.get();
        // 3.计算消耗时间
        long consumeTime = endTime - beginTime;
        
        logger1.debug("监控==========================:"+ String.format("%s consume %d millis", httpServletRequest.getRequestURI(), consumeTime));
        startTimeThreadLocal.remove();
    }
}
